from rest_framework.views import APIView
from django.shortcuts import  render
from .serializers import LoginSerializer,UserSerializer
from datetime import datetime
from .authentications import generate_jwt
from rest_framework.response import Response
from rest_framework import status
from .serializers import ResetPwdSerializer

class LoginView(APIView):
    def post(self, request):
        ## 1、验证 post 数据是否合法 (使用序列验证)
        result = LoginSerializer(data=request.data)
        if result.is_valid():
            ## 验证成功 提取用户 前提是 在序列化的时候 要加入这个
            user = result.validated_data.get('user')
            user.last_login = datetime.now()
            user.save()
            token = generate_jwt(user)
            return Response({"token":token,"user":UserSerializer(user).data},status=status.HTTP_200_OK)
        else:
            print(result.errors)
            ## drf 在响应码是 非200的时候 他的错误参数名叫 detail 这里为了保持统一都叫 detail
            ## {'password': [ErrorDetail(string='该字段不能为空。', code='blank')]}
            return Response({"detail":f"{list(result.errors.values())[0][0]}"},status=status.HTTP_400_BAD_REQUEST)


##重置密码
class RestPwdviews(APIView):
    def post(self, request):
        serializer = ResetPwdSerializer(data=request.data,context={"request":request})
        if serializer.is_valid():
            pwd1 = serializer.validated_data.get('pwd1')
            request.user.set_password(pwd1)
            request.user.save()
            return Response()
        else:
            print(f"验证失败：{serializer.errors}")
            detail = list(serializer.errors.values())[0][0]
            return Response({"detail":detail},status=status.HTTP_400_BAD_REQUEST)